package com.zhht.checkcop.parser;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.zhht.checkcop.db.MysqlDb;
import com.zhht.checkcop.db.StaticDBMap;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

public class Parser88dusChapter implements Pipeline{
	private final static Logger log= Logger.getLogger(Parser88dusChapter.class);
	private String type;
	public Parser88dusChapter(){}
	public Parser88dusChapter(String type){
		this.type=type;
	}
	public void process(ResultItems resultItems, Task arg1) {
		Map<String, Object> mapResults = resultItems.getAll();
        Iterator<Entry<String, Object>> iter = mapResults.entrySet().iterator();
        Map.Entry<String, Object> entry;
        
        List<String> catalog=new ArrayList<String>();
        List<String> catalogName=new ArrayList<String>();
        String description="";
        String imgUrl="";
        String novelUrl="";
        String name="";
        String author_name="";
        
        // 输出到控制台
        while (iter.hasNext()) {
            entry = iter.next();
            if(entry.getKey().equals("catalog")){
            	catalog.addAll((Collection<? extends String>) entry.getValue());
            }
            if(entry.getKey().equals("catalogName")){
            	catalogName.addAll((Collection<? extends String>) entry.getValue());
            }
            if(entry.getKey().equals("description")){
            	description=entry.getValue() + "";
            }
            if(entry.getKey().equals("imgUrl")){
            	imgUrl=entry.getValue() + "";
            }
            if(entry.getKey().equals("novelUrl")){
            	novelUrl = entry.getValue() + "";
            }
            if(entry.getKey().equals("name")){
            	name=entry.getValue() + "";
            }
            if(entry.getKey().equals("author_name")){
            	author_name = entry.getValue() + "";
            }
        }
        
        try{
        	
        	Map<String, Object> exitNovelMap = StaticDBMap.existNovelNameMap.get(novelUrl);
        	
        	//新增
	        if(null != catalog && catalog.size() > 0 && exitNovelMap != null && 0 == Integer.parseInt(exitNovelMap.get("checkSynchronizeType")+"")){
	        	exitNovelMap.put("chapter_count", catalog.size());
	        	exitNovelMap.put("description", description);
	        	exitNovelMap.put("cover_url", imgUrl);
	        	exitNovelMap.put("checkSynchronizeType", 1);
	        	exitNovelMap.put("name", name);
	        	exitNovelMap.put("author_name",author_name);
	        	exitNovelMap.put("thisSyn",1);
	        	
	        	execInsertDB(exitNovelMap, catalog, catalogName, novelUrl);	        	
	        }else if(null != catalog && catalog.size() > 0 && exitNovelMap != null ){//修改
	        	int nowChapterCount=Integer.parseInt(exitNovelMap.get("chapter_count")+"");
	        	if(nowChapterCount!=catalog.size()){
	        		exitNovelMap.put("chapter_count", catalog.size());
	        		exitNovelMap.put("description", description);
	        		exitNovelMap.put("cover_url", imgUrl);
	        		exitNovelMap.put("checkSynchronizeType", 1);
	        		exitNovelMap.put("name", name);
	        		exitNovelMap.put("author_name",author_name);
	        		exitNovelMap.put("thisSyn",1);
		        	execUpdateDB(exitNovelMap, catalog, catalogName, nowChapterCount, novelUrl);
	        	}else{
	        		updateNovelCheckSynchronizeType(exitNovelMap.get("id")+"");
	        	}
	        }else if((null == catalog || catalog.size() == 0) && exitNovelMap != null){
	        	updateNovelCheckSynchronizeType(exitNovelMap.get("id")+"");
	        }
        }catch(Exception e){
    		e.printStackTrace();
    	}
	}
	public Map<String, Object> updateNovelCheckSynchronizeType(String id){
		
		MysqlDb mysqldb = null;
		try{
			mysqldb = new MysqlDb();
			mysqldb.connect();
			
			mysqldb.execute("update novel_info set checkSynchronizeType = 1,thissyn=1 where id = "+id);
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				mysqldb.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public void execInsertDB(Map<String ,Object> updateNovel,List<String> catalog,List<String> catalogName, String novelUrl){
		MysqlDb mysqldb = null;
		try{
			mysqldb = new MysqlDb();
			mysqldb.connect();
			mysqldb.startTrans();
			
			//更新小说
			Map<String ,Object> condition=new HashMap<String, Object>();
			condition.put("id", updateNovel.remove("id"));
			mysqldb.update("novel_info", updateNovel, null, condition);
			
			List<String[]> sqls=new ArrayList<String[]>();
			//批量插入章节
			for(int i=0;i<catalog.size();i++){
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("novel_id", condition.get("id"));
				map.put("cname", catalogName.get(i));
				map.put("sequence", i);
				map.put("url", novelUrl+catalog.get(i));
				sqls.add(mysqldb.assemblyInsertSqls(StaticDBMap.classfiyTableName.get(type).get("tableName")+"",map));
			}
			mysqldb.executeBatchs(sqls);
			mysqldb.commit();
		}catch(Exception e){
			e.printStackTrace();
			try {
				mysqldb.rollback();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally{
			try {
				mysqldb.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void execUpdateDB(Map<String ,Object> updateNovel,List<String> catalog,List<String> catalogName,int nowChapterCount, String novelUrl){
		MysqlDb mysqldb = null;
		try{
			mysqldb = new MysqlDb();
			mysqldb.connect();
			mysqldb.startTrans();
			
			//更新小说
			Map<String ,Object> condition=new HashMap<String, Object>();
			condition.put("id", updateNovel.remove("id"));
			mysqldb.update("novel_info", updateNovel, null, condition);
			
			List<String[]> sqls=new ArrayList<String[]>();
			//批量插入章节
			for(int i=nowChapterCount;i<catalog.size();i++){
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("novel_id", condition.get("id"));
				map.put("cname", catalogName.get(i));
				map.put("sequence", i);
				map.put("url", novelUrl+catalog.get(i));
				sqls.add(mysqldb.assemblyInsertSqls(StaticDBMap.classfiyTableName.get(type).get("tableName")+"",map));
			}
			if(sqls.size()>0){
				mysqldb.executeBatchs(sqls);
			}
			mysqldb.commit();
		}catch(Exception e){
			e.printStackTrace();
			try {
				mysqldb.rollback();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}finally{
			try {
				mysqldb.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
